<template lang="">
  <div class="login_container">
    <div class="login_box">
      <h2>在线教育网后台管理系统</h2>
      <el-form :model="ruleForm" ref="form" label-width="0px" :rules="rules">
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入邮箱" value="27732357@qq.com" prefix-icon="iconfont icon-user"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="ruleForm.password" placeholder="请输入密码" value="123456" type="password" prefix-icon="iconfont icon-lock-fill">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doLogin">登录</el-button>
        </el-form-item>
      </el-form>
      <div class="footer">您没有账户？
        <router-link to="/regist" >点击注册</router-link>
        </div>
    </div> 
  </div>
</template>
<script>
import jwtDecode from 'jwt-decode'
export default {
  name: "Login",
  data() {
    return {
      rules: {
        username: [
          { required: true, message: "您需要输入用户名", trigger: ["blur", "change"] },
          { min: 5, max: 20, message: "用户名长度在5-20之间", trigger: ["blur", "change"] },
          { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] },
        ],
        password: [
          { required: true, message: "您需要输入密码", trigger: ["blur", "change"] },
          { min: 5, max: 20, message: "密码长度在5-20之间", trigger: ["blur", "change"] }
        ],
      },
      ruleForm: {
        username: "27732357@qq.com",
        password: "321321"
      }
    }
  },
  methods: {
    //点击登录按钮
    doLogin() {
      //1. 验证数据
      this.$refs.form.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("用户信息填写不正确")
        }
        //2.提交表单
        var result = await this.$http({
          url: "/api/users/login",
          method: "POST",
          data: {
            email: this.ruleForm.username,
            password: this.ruleForm.password
          }
        }).catch(err => console.log(err))


        if (!result) {
          return this.$message.error(result.message)
        }
        sessionStorage.setItem("token", result.data.token)
        let { name } = jwtDecode(result.data.token)
        console.log(name)
        sessionStorage.setItem("name", name)
        this.$message.success("成功登录")
        this.$router.push("/home")
      })

    }
  }

}
</script>
<style lang="less" scoped>
.login_container {
  width: 100vw;
  /*view width:可见区域宽度*/
  height: 100vh;
  /*view height:可见区域的高度*/
  background: #2d3a4b;
}

.login_box {
  width: 500px;
  height: 300px;
  padding: 20px;

  position: absolute;
  left: 50%;
  top: 50%;

  transform: translate(-50%, -50%);

}

.login_box h2 {
  color: white;
  text-align: center;
}

.el-button {
  width: 100%;
}

.el-input__inner {
  background: #2d3a4b;
  color: white;
}

.footer {
  color: white;
  text-align: right;

  a {
    color: white;
    text-decoration: none;
  }
}
</style>